package com.ruoyi.web.controller.check.patient;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.core.domain.File;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.PageFieldMapper;
import com.ruoyi.system.service.IPageFieldService;
import com.ruoyi.system.service.IPageFieldUserService;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.service.ILabinfoSampleDataService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import static com.ruoyi.common.utils.poi.MapExcelUtil.createExcel;

/**
 * 样本信息Controller
 *
 * @author ruoyi
 * @date 2023-07-03
 */
@RestController
@RequestMapping("/check/sample")
public class LabinfoSampleDataController extends BaseController
{
    @Autowired
    private ILabinfoSampleDataService labinfoSampleDataService;

    @Autowired
    private IPageFieldUserService pageFieldUserService;

    @Autowired
    private PageFieldMapper pageFieldMapper;

    /**
     * 查询样本信息列表
     */
    @PreAuthorize("@ss.hasPermi('check:sample:list')")
    @GetMapping("/list")
    public TableDataInfo list(LabinfoSampleData labinfoSampleData)
    {
        startPage();
        List<LabinfoSampleData> list = labinfoSampleDataService.selectLabinfoSampleDataList(labinfoSampleData);
        return getDataTable(list);
    }

    /**
     * 导出样本信息列表
     */
    @PreAuthorize("@ss.hasPermi('check:sample:export')")
    @Log(title = "样本信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response,LabinfoSampleData labinfoSampleData)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();//获取当前登录信息
        SysUser sysUser = loginUser.getUser();
        if(sysUser != null){
            //根据当前登录人的id，获取 pageFieldUser 表中的对应字段
            PageFieldUser pageFieldUserQuery = new PageFieldUser();
            pageFieldUserQuery.setIsShow("1");
            pageFieldUserQuery.setUserId(sysUser.getUserId());
            pageFieldUserQuery.setPage("sampleCount");
            pageFieldUserQuery.setType(labinfoSampleData.getSampleDecWay());
            List<PageFieldUser> pageFieldUserList = pageFieldUserService.exportFieldList(pageFieldUserQuery);
            if(CollectionUtil.isEmpty(pageFieldUserList)){ //为空，获取默认表中的数据
                boolean isAdmin = false;
                List<PageField> pageFieldList = new ArrayList<>();
                PageField query = new PageField();
                query.setType(pageFieldUserQuery.getType());
                query.setPage(pageFieldUserQuery.getPage());
                //判断当前账号是否为内部员工
                String isRegister = sysUser.getIsRegister();
                if(StringUtils.isNotEmpty(isRegister) && isRegister.equals("1")){ //注册账户，不是内部员工
                    query.setIsStaff("0");
                }else { //内部员工
                    List<SysRole> roleList = sysUser.getRoles();
                    if(CollectionUtil.isNotEmpty(roleList)){ //不为空且角色包含数据管理员和超级管理员
                        for(SysRole sysRole : roleList){
                            if(StringUtils.isNotEmpty(sysRole.getRoleName()) && (sysRole.getRoleName().equals("超级管理员") || sysRole.getRoleName().equals("数据管理员"))){
                                isAdmin = true;
                                break;
                            }
                        }
                    }
                    if(!isAdmin){
                        query.setIsStaff("1");
                    }
                }
                pageFieldList = pageFieldMapper.selectPageFieldList(query);
                if(CollectionUtil.isNotEmpty(pageFieldList)){
                    List<PageFieldUser> tempPageFieldUserList = new ArrayList<>();
                    pageFieldList.stream().forEach(pageField -> {
                        PageFieldUser pageFieldUser1 = new PageFieldUser();
                        pageFieldUser1.setPage(pageField.getPage());
                        pageFieldUser1.setType(pageField.getType());
                        pageFieldUser1.setFieldId(pageField.getId());
                        pageFieldUser1.setSort(pageField.getSort());
                        pageFieldUser1.setFieldNameCn(pageField.getFieldNameCn());
                        pageFieldUser1.setFieldName(pageField.getFieldName());
                        pageFieldUser1.setIsShow("1");
                        tempPageFieldUserList.add(pageFieldUser1);
                    });
                    pageFieldUserList.addAll(tempPageFieldUserList);
                }
            }

            ArrayList<String> fieldNameList = new ArrayList<>();
            ArrayList<String> fieldNameCnList = new ArrayList<>();

            List<PageFieldUser> pageFieldUserListNew = pageFieldUserList.stream().filter(pageFieldUser->StringUtils.isNotEmpty(pageFieldUser.getFieldName()) && StringUtils.isNotEmpty(pageFieldUser.getFieldNameCn())).collect(Collectors.toList());
            for(PageFieldUser pageFieldUser :pageFieldUserListNew){
                if(StringUtils.isNotEmpty(pageFieldUser.getFieldName()) && StringUtils.isNotEmpty(pageFieldUser.getFieldNameCn())){
                    fieldNameList.add(pageFieldUser.getFieldName());
                    fieldNameCnList.add(pageFieldUser.getFieldNameCn());
                }
            }
            List<Map> dataList = labinfoSampleDataService.exportDataList(pageFieldUserListNew,labinfoSampleData,sysUser);
            if(CollectionUtil.isNotEmpty(dataList)){
                createExcel(dataList,fieldNameList,fieldNameCnList,"样本统计导出","样本统计",response);
            }
        }
    }

//    /**
//     * 导出样本信息列表
//     */
//    @PreAuthorize("@ss.hasPermi('check:sample:export')")
//    @Log(title = "样本信息", businessType = BusinessType.EXPORT)
//    @PostMapping("/export")
//    public void export(HttpServletResponse response, LabinfoSampleData labinfoSampleData)
//    {
//        //获取当前登录账号
//        LoginUser loginUser = SecurityUtils.getLoginUser();//获取当前登录信息
//        SysUser sysUser = loginUser.getUser();
//        boolean isAdmin = false;
//        if(sysUser != null){
//            String isRegister = sysUser.getIsRegister() == null? "0":sysUser.getIsRegister() ;//是否注册 1已注册，0未注册
//            if(StringUtils.isNotEmpty(isRegister) && isRegister.equals("1")){//注册，则代表客户
//                List<SampleCustom> list = labinfoSampleDataService.exportSampleCustom(labinfoSampleData,sysUser);
//                ExcelUtil<SampleCustom> util = new ExcelUtil<SampleCustom>(SampleCustom.class);
//                util.exportExcel(response, list, "样本信息数据");
//            }else{ //内部员工和管理员
//                //区分内部员工和管理员（超级管理员或者数据管理员）
//                List<SysRole> roleList = sysUser.getRoles();
//                if(CollectionUtil.isNotEmpty(roleList)){ //不为空且角色包含数据管理员和超级管理员
//                    for(SysRole sysRole : roleList){
//                        if(StringUtils.isNotEmpty(sysRole.getRoleName()) && (sysRole.getRoleName().equals("超级管理员") || sysRole.getRoleName().equals("数据管理员"))){
//                            //包含性染色体核型和样本状态字段
//                            isAdmin = true;
//                            break;
//                        }
//                    }
//                }
//                if(isAdmin){
//                    List<SampleAdmin> list = labinfoSampleDataService.exportSampleAdmin(labinfoSampleData,sysUser);
//                    ExcelUtil<SampleAdmin> util = new ExcelUtil<SampleAdmin>(SampleAdmin.class);
//                    util.exportExcel(response, list, "样本信息数据");
//                }else {
//                    List<SampleStaff> list = labinfoSampleDataService.exportSampleStaff(labinfoSampleData,sysUser);
//                    ExcelUtil<SampleStaff> util = new ExcelUtil<SampleStaff>(SampleStaff.class);
//                    util.exportExcel(response, list, "样本信息数据");
//                }
//            }
//        }
//
//    }

    /**
     * 获取样本信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('check:sample:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(labinfoSampleDataService.selectLabinfoSampleDataById(id));
    }

    /**
     * 新增样本信息
     */
    @PreAuthorize("@ss.hasPermi('check:sample:add')")
    @Log(title = "样本信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody LabinfoSampleData labinfoSampleData)
    {
        return toAjax(labinfoSampleDataService.insertLabinfoSampleData(labinfoSampleData));
    }

    /**
     * 修改样本信息
     */
    @PreAuthorize("@ss.hasPermi('check:sample:edit')")
    @Log(title = "样本信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody LabinfoSampleData labinfoSampleData)
    {
        return toAjax(labinfoSampleDataService.updateLabinfoSampleData(labinfoSampleData));
    }

    /**
     * 删除样本信息
     */
    @PreAuthorize("@ss.hasPermi('check:sample:remove')")
    @Log(title = "样本信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(labinfoSampleDataService.deleteLabinfoSampleDataByIds(ids));
    }


    //根据送检单位和受检人姓名获取受检人所有送检时间
    @PostMapping(value = "/getReceiveSampleDateList")
    public AjaxResult getReceiveSampleDateList(@RequestBody Map map) {
            List<Map> labinfoSampleDataList = labinfoSampleDataService.getReceiveSampleDateList(map);
            return success(labinfoSampleDataList);
    }

    //根据送检单位和受检人姓名获取受检人所有送检时间
    @PostMapping(value = "/getSampleList")
    public AjaxResult getSampleList(@RequestBody Map map) {
        List<LabinfoSampleData> labinfoSampleDataList = labinfoSampleDataService.getSampleList(map);
        return success(labinfoSampleDataList);
    }


    //样本统计 按照类型获取样本数据
    @PreAuthorize("@ss.hasPermi('check:sample:list1')")
    @GetMapping(value = "/getSampleListBySampleDecWay")
    public TableDataInfo getSampleListBySampleDecWay(LabinfoSampleData labinfoSampleData) {
        startPage();
        LoginUser loginUser = SecurityUtils.getLoginUser();//获取当前登录信息
        SysUser sysUser = loginUser.getUser();
        List<Map> list = new ArrayList<>();
        boolean isAdmin = false;
        if(sysUser != null){
            String isRegister = sysUser.getIsRegister() == null? "0":sysUser.getIsRegister() ;//是否注册 1已注册，0未注册
            if(StringUtils.isNotEmpty(isRegister) && isRegister.equals("1")){//注册，则代表客户
                list = labinfoSampleDataService.getSampleListBySampleDecWay(labinfoSampleData,sysUser);
            }else{
                //区分内部员工和管理员（超级管理员或者数据管理员）
                List<SysRole> roleList = sysUser.getRoles();
                if(CollectionUtil.isNotEmpty(roleList)){ //不为空且角色包含数据管理员和超级管理员
                    for(SysRole sysRole : roleList){
                        if(StringUtils.isNotEmpty(sysRole.getRoleName()) && (sysRole.getRoleName().equals("超级管理员") || sysRole.getRoleName().equals("数据管理员"))){
                            isAdmin = true;
                            break;
                        }
                    }

                }
                list = labinfoSampleDataService.getLabinfoSampleDataList(labinfoSampleData,isAdmin);
            }

        }
        return getDataTable(list);
    }

    /**
     * 分享内容
     */
//    @PreAuthorize("@ss.hasPermi('system:custom:audit')")
    @PutMapping("/shareSamples")
    @Log(title = "分享样本统计", businessType = BusinessType.SHARE)
    public AjaxResult shareSamples(@RequestBody LabinfoSampleData labinfoSampleData)
    {
        return toAjax(labinfoSampleDataService.shareSamples(labinfoSampleData));
    }





}
